//index.js
import api from "../../api/cloudApi.js"
//获取应用实例
const app = getApp()
let courseOpt = {
  maths: {
    key: 'maths',
    label: '数学',
    start_time: '',
    end_time: ''
  },
  chinese: {
    key: 'chinese',
    label: '语文',
    start_time: '',
    end_time: ''
  },
  english: {
    key: 'english',
    label: '外语',
    start_time: '',
    end_time: ''
  },
  physical: {
    key: 'physical',
    label: '物理',
    start_time: '',
    end_time: ''
  },
  chemistry: {
    key: 'chemistry',
    label: '化学',
    start_time: '',
    end_time: ''
  },
  history: {
    key: 'history',
    label: '历史',
    start_time: '',
    end_time: ''
  },
  politics: {
    key: 'politics',
    label: '政治',
    start_time: '',
    end_time: ''
  }
}
Page({
  data: {
    ctx: '',
    userInfo: {},
    timer: 0,
    intervalId: '',
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    latitude: 0,
    longitude: 0,
    speed: 0,
    accuracy: 0,
    markers: [],
    isUploadedLocation: false,
    recordingCourse: 'maths',
    isPress: false,
    windowWidth: 0,
    selfMode: false,
    courseList: JSON.parse(JSON.stringify(courseOpt)),
    selfCourseList: JSON.parse(JSON.stringify(courseOpt)),
    hadRecord: false
  },
  //事件处理函数
  bindViewTap: function() {
    this.setData({
      selfMode: !this.data.selfMode
    })
    var modeText = this.data.selfMode ? '自学' : '作业'


    this.hasEnd()
    wx.showToast({
      title: '已更换为' + modeText + '模式',
    })
  },
  reloadPageData() {
    let data = app.globalData.recordingCourseData;
    if (data && data.start_time) {
      console.log('reload', data)
      let targetCourses = this.data.selfMode ? 'selfCourseList' : 'courseList'
      let prefix = targetCourses + '.' + data.key + '.start_time'
      this.setData({
        recordingCourse: data.key,
        selfMode: data.selfMode,
        [prefix]: data.start_time
      })
      this.startTimer()
      app.globalData.recordingCourseData = {}
    }
  },
  onLoad: function() {
    this.pageDataInit();
  },

  onShow() {
    console.log('onShow')

    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回  所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => this.setData({
        userInfo: res.userInfo,
        hasUserInfo: true
      });
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
  },

  // 初始化数据库等页面数据
  pageDataInit: async function() {
    let isUploaded = await api.hasUploadLocation(); // 判断是否已经定位过
    if (isUploaded) {
      this.getTodayCourseInfo();
    }
    this.setData({
      isUploadedLocation: isUploaded
    });
    this.getLocation();
    this.reloadPageData()
  },

  // 获取定位信息
  getLocation: async function() {
    let _this = this;
    await wx.getLocation({
      type: 'gcj02',
      success: async function(res) {
        var latitude = res.latitude
        var longitude = res.longitude
        _this.setData({
          latitude: res.latitude,
          longitude: res.longitude,
          markers: [{
            id: "1",
            latitude: res.latitude,
            longitude: res.latitude,
            width: 50,
            height: 50,
            iconPath: "/images/game.png",
            title: "哪里"
          }]
        })
      }
    })
  },

  // 获取当日课程打卡信息
  async getTodayCourseInfo() {
    console.log('getCourseInfo')
    let res = await api.getTodayCourseInfo();
    res = res.data[0]
    Object.keys(courseOpt).forEach((key, i) => {
      let prefix = 'courseList.' + key
      res[key] ? this.setData({
        [prefix + '.start_time']: res[key].start_time,
        [prefix + '.end_time']: res[key].end_time
      }) : ''

      if (res['self']) {
        let selfPrefix = 'selfCourseList.' + key
        res['self'][key] ? this.setData({
          [selfPrefix + '.start_time']: res['self'][key].start_time,
          [selfPrefix + '.end_time']: res['self'][key].end_time
        }) : ''
      }
    })

    this.hasEnd();
  },

  // 上传定位信息
  async uploadLocation() {
    let res = await wx.cloud.callFunction({
      name: "uploadLocation",
      data: {
        latitude: this.data.latitude,
        longitude: this.data.longitude
      }
    })
    if (res) {
      this.setData({
        isUploadedLocation: true
      });
    }
    wx.showToast({
      title: res ? '上传成功' : '上传失败 请重新上传',
      icon: res ? 'success' : 'none'
    })
  },

  // 开始计时
  startTimer(e) {
    if (!this.data.isUploadedLocation) {
      this.uploadLocation()
      return;
    }
    if (this.data.intervalId) return; // 存在计时器时说明未结束，不能开始新的计时 

    let targetCourses = this.data.selfMode ? 'selfCourseList' : 'courseList';
    let courseList = this.data[targetCourses][this.data.recordingCourse]
    if (courseList.end_time) return;
    courseList.start_time = courseList.start_time || new Date(); // 记录开始时间
    let formatTime = ~~((new Date() - courseList.start_time) / 1000)
    let intervalId = setInterval(() => {
      console.log(courseList.start_time, formatTime)
      this.setData({
        timer: this.timerFormater(++formatTime)
      });
    }, 1000)
    this.setData({
      intervalId
    });
  },
  // 停止计时
  stopTimer() {
    clearInterval(this.data.intervalId);
    this.setData({ // 重置计数器参数
      timer: 0,
      intervalId: ''
    });

    let targetCourses = this.data.selfMode ? 'selfCourseList' : 'courseList';
    let course = this.data[targetCourses][this.data.recordingCourse]
    course.end_time = new Date()

    let res = api.uploadCourse(this.data.recordingCourse, course, this.data.selfMode)
    wx.showToast({
      title: res ? '上传成功' : '上传失败 请重新上传',
      icon: res ? 'success' : 'none'
    })
  },
  // 长按开始 开始绘制环形进度条
  timerTouchStart() {
    if (!this.data.intervalId) return; // 不存在计时器 则退出
    this.setData({
      isPress: true
    });
    setTimeout(() => {
      this.couldCloseTimer()
    }, 2000);
  },

  couldCloseTimer() {
    if (this.data.isPress) {
      this.timerTouchEnd()
      this.stopTimer()
    } else {
      wx.showToast({
        title: '结束失败，请重试',
        icon: 'none'
      })
    }

  },

  // 长按结束 
  timerTouchEnd() {
    if (!this.data.intervalId) return; // 不存在计时器 则退出
    this.setData({
      isPress: false
    });
  },

  timerFormater(time) {
    let times = [~~(time / 3600), ~~(time / 60), time % 60]
    return times.map(t => t < 10 ? '0' + t.toString() : t).join(':')
  },

  changeCourse(e) {
    if (this.data.intervalId) {
      wx.showToast({
        title: '--当前科目正在进行中--  长按结束后就可以切换了',
        icon: 'none',
        duration: 2000
      })
      return
    }
    let key = e.currentTarget.dataset.key
    this.setData({
      recordingCourse: key
    })
    this.hasEnd();
  },

  hasEnd() {
    let targetCourses = this.data.selfMode ? 'selfCourseList' : 'courseList',
      hasEnded = false
    let courseList = this.data[targetCourses][this.data.recordingCourse]
    this.setData({
      hasEnd: Boolean(courseList.end_time)
    })
  },
  clearCanvas() {
    this.data.ctx.clearRect(0, 0, this.data.windowWidth, this.data.windowWidth)
    this.data.ctx.draw()
  },

  getUserInfo: function(e) {
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  onHide: function() {
    console.log('onHide')
  },
  onUnload: function() {
    if (this.data.intervalId) {
      clearInterval(this.data.intervalId)
      let targetCourses = this.data.selfMode ? 'selfCourseList' : 'courseList'
      let courseData = this.data[targetCourses][this.data.recordingCourse]
      app.globalData.recordingCourseData = Object.assign(courseData, {
        selfMode: this.data.selfMode
      })
    }
  },
})